﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using YGame.Base;
using YGame.Base.Message;

namespace YGame.GameLogic
{
	public class GameLogicProvider : IGameLogic
	{
		private Dictionary<int, IActor> ActorMap;
		private ClientMsgDispatcher clientMsgDispatcher;

		public event EventHandler Login;
		public event EventHandler Logout;

		public GameLogicProvider()
		{
			ActorMap = new Dictionary<int, IActor>();
			clientMsgDispatcher = new ClientMsgDispatcher();
		}


		public void Install(IGameServerProvider gameProvider)
		{
			Trace.WriteLine("YGame.GameLogic install.\r\n", YGame.Base.TraceType.Info.ToString());
			//ThingRepository.Init();


			/// 初始化 thing server
			YGame.Base.ServerGlobal.GameThingProvider = new YGame.GameThing.GameThingProvider();
			YGame.Base.ServerGlobal.GameThingProvider.Install(this);

			clientMsgDispatcher.Init(gameProvider);
			clientMsgDispatcher.AddListener(typeof(YGame.GameLogic.MessageHandler.ActorLogin));

		}

		public void Uninstall()
		{
			Trace.WriteLine("YGame.GameLogic uninstall.\r\n", YGame.Base.TraceType.Info.ToString());
			//ThingRepository.Release();

			YGame.Base.ServerGlobal.GameThingProvider.Uninstall();
		}



		public IActor GetActor(int actorID)
		{
			return ActorMap[actorID];
		}

		public IActor ActorLogin(int actorID)
		{
			if (ActorMap.ContainsKey(actorID))
			{
				Trace.WriteLine(String.Format("actor[{0}] repleat login!", actorID), "Error");
				return null;
			}
			Actor actor = ActorBuilder.CreateActor(actorID);
			actor.Load();
			ActorMap[actorID] = actor;
			actor.OnLogin();
			if (Login != null)
			{
				Login(actor, EventArgs.Empty);
			}

			Trace.WriteLine(string.Format("GameServerProvider: actor login: {0}", actor.ActorID));
			return actor;
		}

		public bool ActorLogout(int actorID)
		{
			if (!ActorMap.ContainsKey(actorID))
			{
				Trace.WriteLine(String.Format("actor[{0}] not login!", actorID), "Error");
				return false;
			}

			Actor actor = ActorMap[actorID] as Actor;
			actor.OnLogout();
			if (Logout != null)
			{
				Logout(actor, EventArgs.Empty);
			}
			ActorMap.Remove(actorID);
			actor.Save();
			actor.Release();
			Trace.WriteLine(string.Format("GameServerProvider: actor logout: {0}", actor.ActorID));
			return true;
		}

	}
}
